
// 获取应用实例
const app = getApp()

Page({
  data: {
    region: ['浙江省', '杭州市', '上城区', '丁兰街道'], // 默认设置为浙江省-杭州市-上城区
    range: 1, // 默认1km
    visibility: {
      province: false,
      city: false,
      district: true,
      street: true
    },
    customMessage: ''
  },

  onLoad() {
    // 确保 settings 对象存在
    if (!app.globalData.settings) {
      app.globalData.settings = {
        region: ['浙江省', '杭州市', '上城区', '丁兰街道'],
        range: 1,
        visibility: {
          province: false,
          city: false,
          district: true,
          street: true
        },
        message: '老乡见老乡，两眼泪汪汪！'
      }
    }
    
    // 从全局数据初始化设置
    this.setData({
      range: app.globalData.settings.range || 1,
      visibility: app.globalData.settings.visibility || {
        province: false,
        city: false,
        district: true,
        street: true
      },
      region: app.globalData.settings.region || ['浙江省', '杭州市', '上城区', '丁兰街道'],
      customMessage: app.globalData.settings.message || '老乡见老乡，两眼泪汪汪！'
    })
    
    // 初始化全局地区设置
    if (!app.globalData.settings.region) {
      app.globalData.settings.region = this.data.region
    }
  },

  // 地区选择变化
  onRegionChange(e) {
    const { value } = e.detail
    this.setData({ region: value })
    app.globalData.settings.region = value
    wx.setStorageSync('settings', app.globalData.settings)
  },

  // 范围调节
  onRangeChange(e) {
    const range = e.detail.value
    this.setData({ range })
    app.globalData.settings.range = range
    wx.setStorageSync('settings', app.globalData.settings)
  },

  // 隐私设置变化
  onVisibilityChange(e) {
    const { type } = e.currentTarget.dataset
    const { visibility } = this.data
    visibility[type] = !visibility[type]
    
    this.setData({ visibility })
    app.globalData.settings.visibility = visibility
    wx.setStorageSync('settings', app.globalData.settings)
  },

  // 自定义消息输入
  onMessageInput(e) {
    this.setData({ customMessage: e.detail.value })
  },

  // 保存设置
  saveSettings() {
    // 确保 settings 对象存在
    if (!app.globalData.settings) {
      app.globalData.settings = {}
    }
    
    // 保存所有设置
    app.globalData.settings.region = this.data.region
    app.globalData.settings.range = this.data.range
    app.globalData.settings.visibility = this.data.visibility
    app.globalData.settings.message = this.data.customMessage || '老乡见老乡，两眼泪汪汪！'
    
    // 持久化存储
    wx.setStorageSync('settings', app.globalData.settings)
    
    wx.showToast({
      title: '设置已保存',
      icon: 'success',
      duration: 1500
    })
    
    setTimeout(() => {
      wx.navigateBack()
    }, 1500)
  }
})